package com.fatri.lessionsimple

import android.os.Build
import android.os.Bundle
import android.os.Environment
import androidx.appcompat.app.AppCompatActivity
import com.fatri.lessionsimple.audio.AudioTrackManager
import com.fatri.lessionsimple.util.OpenSLNative
import kotlinx.android.synthetic.main.act_audio.*
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File


class AudioActivity : AppCompatActivity() {
    /**
     * 播放 path
     */
    private var PATH =
        Environment.getExternalStorageDirectory().toString() + "/_test.pcm"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.act_audio)
        checkFile()
        initView()
    }

    private fun checkFile() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            PATH = getExternalFilesDir(Environment.DIRECTORY_MOVIES)!!.path
            val dir = File(PATH)
            if (!dir.exists()) dir.mkdirs()
            val file = File(PATH, "_test.pcm")
            if (!file.exists()) {
                file.createNewFile()
                val ins = assets.open("_test.pcm")
                val bis = BufferedInputStream(ins)
                val bos = BufferedOutputStream(file.outputStream())

                var length = 0
                val byteArray = ByteArray(1024)
                while (true) {
                    length = bis.read(byteArray)
                    if (length == -1) break
                    bos.write(byteArray, 0, length)
                }
                ins.close()
                bos.close()
                bis.close()
            }

            PATH = file.path

        }
    }

    private var SLplayer: OpenSLNative? = null
    private fun initView() {
        btn_record.setOnClickListener {

        }

        btn_at_play.setOnClickListener {
            val mgr = AudioTrackManager()
            mgr.init(this)
            mgr.play(PATH)
        }

        btn_sl_play.setOnClickListener {
            SLplayer = OpenSLNative()
            SLplayer!!.startPlay(PATH)
        }
        btn_sl_stop.setOnClickListener {
            SLplayer!!.stopPlay()
        }
    }
}